<?php
/*
 * 某位程序想出了一个压缩字符串的方法，压缩后的字符串如下: 3{a}2{bc}，3{a2{c}}，2{abc}3{cd}ef，
 * 现在 需要你写一个解压的程序，还原原始的字符串。如:
 * s = "3{d}2{bc}", return "dddbcbc".
 * s = "3{a2{d}}", return "addaddadd".
 * s = "2{efg}3{cd}ef", return "efgefgcdcdcdef".
 * 重复次数可以确保是一个正整数。
 */

$arr = ["3{d}2{bc}", "3{a2{d}}", "2{efg}3{cd}ef"];
$obj = new Code_03_DecompressString();
$obj->main($arr);

class StringObj
{
    public $str;
    public $end;

    public function __construct($str, $index)
    {
        $this->str = $str;
        $this->end = $index;
    }
}

class Code_03_DecompressString
{
    public function main($arr)
    {
        foreach ($arr as $str) {
            echo "$str ==> ";
            $res = $this->_decodeString($str, 0);
            echo $res->str . PHP_EOL;
        }
    }

    protected function _decodeString($str, $index)
    {
        $res = '';
        $times = 0;
        $len = strlen($str);
        while ($index < $len && $str[$index] != '}') {
            if ($str[$index] == '{') {
                $obj = $this->_decodeString($str, $index+1);
                $res .= str_repeat($obj->str, $times);
                $times = 0;
                $index = $obj->end + 1;
            } else {
                if (ord($str[$index]) >= ord('0') && ord($str[$index]) <= ord('9')) {
                    $times = $times * 10 + ord($str[$index]) - ord('0');
                }
                if (ord($str[$index]) >= ord('a') && ord($str[$index]) <= ord('z')) {
                    $res .= $str[$index];
                }
                $index++;
            }
        }
        return new StringObj($res, $index);
    }
}